package com.ourcraft.informationcollectionsystem.service.province.filingInfoQuery;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.City;
import com.ourcraft.informationcollectionsystem.entity.Company;
import com.ourcraft.informationcollectionsystem.mapper.CityMapper;
import com.ourcraft.informationcollectionsystem.mapper.CompanyMapper;
import com.ourcraft.informationcollectionsystem.utils.ExportAndSendExcel;
import com.ourcraft.informationcollectionsystem.utils.LowerCamelToLowerUnderscore;
import com.ourcraft.informationcollectionsystem.utils.statusCode.CompanyRecordStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FilingInfoQueryServiceImpl implements FilingInfoQueryService{
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CityMapper cityMapper;

    @Override
    public List<Company> getRequiredFilingInfoList(JSONObject cond) {
        var simple_cond = LowerCamelToLowerUnderscore.exec_json(cond.getJSONObject("simple"));
        var city_name = cityMapper.selectOne(
                new QueryWrapper<City>().eq("user_id", simple_cond.getInteger("companyCity")));
        simple_cond.put("company_city", city_name == null ? null : city_name.getCityName());

        // simple_cond含有仅需要精确比较的字段，前端添加新内容时不需要修改后端
        var location = cond.getObject("companyLocation", ArrayList.class);
        var chineseName = cond.getString("companyChineseName");
        var queryWrapper = new QueryWrapper<Company>()
                .allEq((k,v) -> v != null && v != "", simple_cond)
                .in(location != null && !location.isEmpty(), "company_location", location)
                .like(chineseName != null && !chineseName.isEmpty(), "company_chinese_name", chineseName)
                .eq("company_record_status", CompanyRecordStatus.PASS.ordinal());
        return companyMapper.selectList(queryWrapper);
    }

    @Override
    public ResponseEntity<Resource> exportCurrentFilingInfoList(JSONObject cond) {
        List<Company> queriedData = getRequiredFilingInfoList(cond);
        var exportExcel = new ExportAndSendExcel(Company.class);
        exportExcel.export(queriedData);

        return exportExcel.send();
    }
}
